package me.spring.cloud.components.starter.security.access.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import me.spring.cloud.common.components.response.util.CommonResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * 授权失败(forbidden)时返回信息
 * @author: luffy
 * @create: 2018-08-15 14:29
 **/
public class AuthAccessDeniedHandler implements AccessDeniedHandler {

  @Autowired
  private ObjectMapper objectMapper;

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response,
      AccessDeniedException accessDeniedException) throws IOException, ServletException {
    response.setContentType("application/json;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write(
        objectMapper.writeValueAsString(CommonResponseUtil.error(accessDeniedException.getMessage())));
  }
}
